package top.heue.utils.base.helper.item

import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import top.heue.utils.RA
import java.util.*

/**
 * 拖拽功能，用法：this.attachToRecyclerView(recyclerView)
 */
class ItemTouchCallback<T>(private val adapter: RA<T>) : ItemTouchHelper.Callback() {

    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {
        var dragFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
        if (recyclerView.layoutManager is GridLayoutManager)
            dragFlags = dragFlags or ItemTouchHelper.UP or ItemTouchHelper.DOWN
        val swipeFlags = 0
        return makeMovementFlags(dragFlags, swipeFlags)
    }

    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        val fromPosition = viewHolder.adapterPosition
        val toPosition = target.adapterPosition
        if (fromPosition < toPosition)
            for (i in fromPosition until toPosition)
                Collections.swap(adapter.allItem, i, i + 1)
        else
            for (i in fromPosition downTo toPosition + 1)
                Collections.swap(adapter.allItem, i, i - 1)
        adapter.notifyItemMoved(fromPosition, toPosition)
        //Log.d("MOVE", "$fromPosition-$toPosition")
        return true
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {

    }

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        super.onSelectedChanged(viewHolder, actionState)
        /*if (actionState != ItemTouchHelper.ACTION_STATE_IDLE)
            viewHolder?.itemView?.setBackgroundColor(Color.LTGRAY)*/
    }

    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        super.clearView(recyclerView, viewHolder)
        /*viewHolder.itemView.setBackgroundColor(0)*/
    }

    override fun isLongPressDragEnabled(): Boolean {
        return false
    }

    override fun isItemViewSwipeEnabled(): Boolean {
        return super.isItemViewSwipeEnabled()
    }
}